/**
 * 
 * 
 */
$(function() {
	var liList = $(".main ul li");
	$(".main ul li").each(function(index, item) {
		//使用li做定位，与span的位置相同并给span添加index属性作为标识
		var _span = $(this).css({ 
			"left": index * $(this).width() + 10 * index
		}).after(()=>"<span>"+randomUtils.int(100)+"</span>").next().attr("index",index).css({
			"left": index * $(this).width() + 10 * index,
			"z-index":999
		})[0];
		
		new dragEle(_span).init();
	});
});

function mousePoint(e) {
	this.X=e.clientX + document.body.scrollLeft || document.documentElement.scrollLeft;
	this.Y=e.clientY + document.body.scrollTop || document.documentElement.scrollTop;
}
function mouseOffsetPoint(e){
	this.X=e.offsetX;
	this.Y=e.offsetY;
}
function dragEle(ele) {
	this.count = 0;
	this.init = function() {
		this.ele = ele;
		this.drag();
	}
	this.drag = function() {
		var _this = this;
		$(this.ele).on('mousedown', function(e) {
			$(this.ele).stop().css({
				"opacity":0.8,
				"z-index":99 //改变层级，使得在碰撞时其他元素能被选中
			});
			var mouseInitialPosition = new mouseOffsetPoint(e); //鼠标相对点击元素的坐标
			var _mousemove = function(e) {//鼠标点击后跟随移动函数
				e = e || window.event;
				//鼠标相距页面的坐标
				var mouseCurrenPosition = new mousePoint(e);
				$(this).css({
					left: mouseCurrenPosition.X - $(this).parent().offset().left - mouseInitialPosition.X,
					top: mouseCurrenPosition.Y - $(this).parent().offset().top - mouseInitialPosition.Y
				});
			}.bind(this.ele);
			$(document).on("mousemove", _mousemove);// 绑定移动函数
			$(document).one("mouseup",function(e){//鼠标抬起解绑,且只监听一次
				e = e || window.event;
				$(this).off("mousemove", _mousemove);
				var mouseUpPoint = new mousePoint(e);
				
				_this.impact(e.target);
			});
			e.stopPropagation();
		}.bind(this));

		return this;
	}
	this.impact = function(end){
		var _this = this;
		var end = end;
		if(this.ele==end){//如果停止时仍是自身则返回原来位置
			var targetPoint = $(this.ele).siblings("li").eq($(this.ele).attr("index"));//找到原定位的li
			$(this.ele).animate({
				"left":targetPoint.css("left"),
				"top":targetPoint.css("top"),
				"opacity":1,
				"z-index":999
			},2000);
		}else{ //若是其他元素则交换
			var swapA = $(this.ele);
			var swapB = $(end);
			//交换index值
			var tmp = swapA.attr("index");
			swapA.attr("index",swapB.attr("index"));
			swapB.attr("index",tmp);
			//交换位置
			var targetPointA = swapA.siblings("li").eq(swapA.attr("index"));
			swapA.animate({
				"left":targetPointA.css("left"),
				"top":targetPointA.css("top"),
				"opacity":1,
				"z-index":999
			},2000);
			var targetPointB = swapB.siblings("li").eq(swapB.attr("index"));
			swapB.animate({
				"left":targetPointB.css("left"),
				"top":targetPointB.css("top")
			},2000);
			 
			 
		}
	}
}